package com.yida.common.core.utils.ip;

import java.io.InputStream;
import java.net.InetAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.yida.common.core.utils.memory.MemoryUtils;

/**
 * @author Administrator
 * @date 2023/11/10
 */
public class GeoLite2Utils {

    private static final Logger log = LoggerFactory.getLogger(GeoLite2Utils.class);

    private static DatabaseReader reader;

    // 设置静态
    static {
        try {
            ClassPathResource resource = new ClassPathResource("GeoLite2-City.mmdb");
            InputStream inputStream = resource.getInputStream();
            // 如果最大内存足够则加载
            if (MemoryUtils.getMaxMemoryInfo() > inputStream.available()) {
                reader = new DatabaseReader.Builder(inputStream).build();
            }
            log.info("加载了GeoLite2-City.mmdb文件,reader初始化完成!");
        } catch (Exception e) {
            log.error("初始化GeoLite2-City.mmdb文件失败,报错信息:[{}]", e.getMessage(), e);
            throw new RuntimeException("系统异常!");
        }
    }

    /**
     * description 地址库查询
     *
     * @param ip 地址
     * @return java.lang.String
     * @version 1.0
     */
    public static String getRealAddress(String ip) {
        if (IpUtils.internalIp(ip)) {
            return "本地网络";
        }
        String result = "未知网络";
        try {
            // 空情况下不操作
            if (reader == null) {
                return result;
            }
            // 加载地址库
            // ClassPathResource resource = new ClassPathResource("GeoLite2-City.mmdb");
            // DatabaseReader reader = new DatabaseReader.Builder(resource.getInputStream()).build();
            InetAddress inetAddress = InetAddress.getByName(ip);
            CityResponse response = reader.city(inetAddress);
            System.out.println("response:" + response);
            // 获取所在国家
            String country = response.getCountry().getNames().get("ja");
            System.out.println("1:" + response.getSubdivisions());
            // 1 由库内获取IP信息
            if (response.getSubdivisions().size() > 0) {
                // 获取所在省份
                String province = response.getSubdivisions().get(0).getNames().get("zh-CN");
                // 获取所在城市
                String city = response.getCity().getNames().get("zh-CN");
                city = city == null ? "" : city;
                result = country + province + city;
            }
            // else {
            // // 库内获取不到的IP，访问ali的地域查询
            // result = getAlibaba(ip);
            // }
            // reader.close();
        } catch (Exception e) {
            log.error("未知网络", e);
            return "未知网络";
        }
        return result;
    }

    public static void main(String[] args) {
        // System.out.println(GeoLite2Utils.getRealAddress("110.88.161.105"));
        System.out.println(GeoLite2Utils.getRealAddress("222.77.4.31"));
        // ClassPathResource resource = new ClassPathResource("GeoLite2-City.mmdb");
        // try {
        // System.out.println("1:" + resource.getInputStream().available() / 1024 / 1024);
        // System.out.println("2:" + MemoryUtils.getMaxMemoryInfo() / 1024 / 1024);
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
    }

}
